package net.zjitc.stack.expression;

import net.zjitc.stack.MyLinkedStack;
import net.zjitc.stack.MyStack;

public class BackExpression {

    /**
     * 后序表达式求值算法
     * @param s  后序表达式
     * @return 表达式的值
     */
    private static int evaluatePostfix(String s)
    {
        //将表达式字符串转成字符串数组，方便后序处理
        String[] params = s.split(" ");
        //用于存放操作数的栈
        MyStack<Integer> stack = new MyLinkedStack<>();
        //算法
        for (String param : params) {
            if (param.equals("+")) {
                int d2 = stack.pop();
                int d1 = stack.pop();
                stack.push(d1 + d2);
            } else if (param.equals("-")) {
                int d2 = stack.pop();
                int d1 = stack.pop();
                stack.push(d1 - d2);
            } else if (param.equals("*")) {
                int d2 = stack.pop();
                int d1 = stack.pop();
                stack.push(d1 * d2);
            } else if (param.equals("/")) {
                int d2 = stack.pop();
                int d1 = stack.pop();
                stack.push(d1 / d2);
            } else { // number
                stack.push(Integer.parseInt(param));
            }
        }
        //返回栈顶元素，也就是表达式的值
        return stack.pop();
    }
}
